<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Withdrawal as WithdrawalModel;
use app\payment\model\WithdrawalAlipay as WithdrawalAlipayModel;
use app\payment\model\BankCard as BankCardModel;
use app\payment\model\PaymentCash as PaymentCash;
use app\payment\model\Mconfig as MconfigModel;
use app\payment\model\Download as DownloadModel;
use app\admin\model\Attachment;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 提现控制器
 */
class Withdrawal extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'index_alipay', 'see', 'see_alipay', 'add', 'add_alipay', 'export', 'export_alipay', 'up'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'now_cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];
        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
            $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中'];
        }

        //        if ($this->is_agent) {
        //            $sub_merchant = get_sub_merchant($this->merchant_id);
        //            if ($sub_merchant) {
        //                $sub_merchant[] = $this->merchant_id;
        //                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
        //                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
        //                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
        //                }
        //            }
        //        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = WithdrawalModel::where($map)->order('create_time desc')->paginate($list_rows);

        $sum_count = WithdrawalModel::where($map)->count();
        $sum_cash = WithdrawalModel::where($map)->sum('cash');
        $sum_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        $all_bank_type = ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡'];
        $all_account_type = ['私户' => '私户', '公户' => '公户'];

        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '状态', '', '', $all_withdrawal_status],
            ['select:3', 'bank_type', '银行卡类型', '', '', $all_bank_type],
            ['select:3', 'account_type', '账户类型', '', '', $all_account_type],
            ['text:3', 'bank_card', '收款银行卡'],
            ['text:3', 'name', '收款人姓名'],
            ['text:3', 'mobile', '收款人手机号'],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'cash', '金额'],
            ['text:3', 'now_cash', '到账金额'],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['order_id', '平台订单号'],
            ['name', '收款人姓名'],
            ['bank_card', '收款银行卡'],
            ['area', '地区', 'callback', function ($value) {
                return $value['bank_name'] . $value['province'] . $value['city'] . $value['account_opening_branch'];
            }, '__data__', 'text-center'],
            ['cash', '提现金额（元）', 'callback', function ($cash) {
                return $cash / 100;
            }],
            ['now_cash', '到账金额（元）', 'callback', function ($now_cash) {
                if ($now_cash == 0) {
                    return '';
                }
                return $now_cash / 100;
            }],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_withdrawal_status],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[10]);
            unset($search[11]);
            // 去掉显示列
            unset($items[0]);
            unset($items[4]);
        }
        //        if ($this->is_agent) {
        //            // 显示搜索项
        //            $search[] = ['text:3', 'merchant_id', '商户号'];
        //            // 显示列
        //            array_unshift($items, ['merchant_id', '商户', 'callback', function($value) {
        //                    return $value . '<br/>' . get_user_nickname($value);
        //                }, '', 'text-center']);
        //        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $max_withdrawal_apply_count = pay_config('max_withdrawal_apply_count');

        $down = "<a title='下载模板' class='btn btn-xs btn-success' href='/common/template.xls' target='_blank' data-toggle='tooltip' data-original-title='下载模版'><i class='fa fa-fw fa-arrow-circle-down'></i>下载模版</a>";

        $up = "<a title='选择文件' class='btn btn-xs btn-warning' href='up' data-toggle='tooltip' data-original-title='选择文件'><i class='fa fa-fw fa-arrow-circle-up'></i>选择文件</a>";

        $tips = "批量提现模板下载  {$down}  友情提醒：首次批量上传，请先下载模板文件，并根据模板文件内容仔细填写！<br/><br/>批量提现文件上传  {$up}  友情提醒：请务必保证按照下载模板文件内容进行填写！文件过大时可能要上传一段时间，请耐心等待！<br/><br/>系统设置最多存在申请提现状态为｛{$max_withdrawal_apply_count}｝个！";
        $tips = '';

        $add_withdrawal = <<<EOF
<a title="申请提现" style="margin-bottom:6px;" class="btn btn-nm btn-primary" href="add" >
<i class="fa fa-plus-circle"></i>
申请提现
</a> 
EOF;

        $add_withdrawal_alipay = <<<EOF
<a title="支付宝提现" style="margin-bottom:6px;" class="btn btn-nm btn-success" href="index_alipay" >
<i class="fa fa-plus-circle"></i>
支付宝提现
</a> 
EOF;

        if ($this->no_auth) {
            $info = MconfigModel::where(['id' => $this->merchant_id, 'status' => 1])->find();
            if (false === strpos($info['trade_type'], 'withdrawal')) {
                $add_withdrawal = '';
                $add_withdrawal_alipay = '';
                $tips = '';
            }

            // 是否开启支付宝提现
            if ($this->merchant_info['alipay_withdrawal'] == 0) {
                $add_withdrawal_alipay = '';
            }
        }

        // 是否开启手动提现
        if ($this->merchant_info['manual_withdrawal'] == 0) {
            $add_withdrawal = '';
            $add_withdrawal_alipay = '';
            $tips = '';
        }

        if (!$this->no_auth) {
            $alipay_withdrawal_count = WithdrawalAlipayModel::where(['status' => 0])->count();
            $alipay_withdrawal_count_cash = WithdrawalAlipayModel::where(['status' => 0])->sum('cash');
            $alipay_withdrawal_count_cash /= 100;
            if ($alipay_withdrawal_count > 0) {
                $tips = "<font size='3' color='#f0ad4e'>支付宝申请提现有{$alipay_withdrawal_count}个，总金额为{$alipay_withdrawal_count_cash}元！</font><br/>" . $tips;
            }
            $bank_withdrawal_count = WithdrawalModel::where(['status' => 0])->count();
            $bank_withdrawal_count_cash = WithdrawalModel::where(['status' => 0])->sum('cash');
            $bank_withdrawal_count_cash /= 100;
            if ($bank_withdrawal_count > 0) {
                $tips = "<font size='3' color='#f0ad4e'>银行卡申请提现有{$bank_withdrawal_count}个，总金额为{$bank_withdrawal_count_cash}元！</font><br/>" . $tips;
            }
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('提现列表') // 设置页面标题
            ->setTableName('payment_withdrawal') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->setSearchArea($search) // 设置搜索参数
            ->setPageTips($tips)
            ->hideCheckbox()
            ->addColumns($items)
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->setExtraHtml($add_withdrawal, 'toolbar_top')
            ->setExtraHtml($add_withdrawal_alipay, 'toolbar_bottom')
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->replaceRightButton(['status' => ['not in', '0,3,4']], '', 'edit') // 替换右侧按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 首页支付宝
     * @return mixed
     */
    public function index_alipay()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'now_cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];
        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
            $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中'];
        }

        //        if ($this->is_agent) {
        //            $sub_merchant = get_sub_merchant($this->merchant_id);
        //            if ($sub_merchant) {
        //                $sub_merchant[] = $this->merchant_id;
        //                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
        //                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
        //                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
        //                }
        //            }
        //        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = WithdrawalAlipayModel::where($map)->order('create_time desc')->paginate($list_rows);

        $sum_count = WithdrawalAlipayModel::where($map)->count();
        $sum_cash = WithdrawalAlipayModel::where($map)->sum('cash');
        $sum_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '状态', '', '', $all_withdrawal_status],
            ['text:3', 'mobile', '收款人手机号'],
            ['text:3', 'account', '支付宝帐号'],
            ['text:3', 'name', '姓名'],
            ['text:3', 'cash', '金额'],
            ['text:3', 'now_cash', '到账金额'],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['order_id', '平台订单号'],
            ['name', '姓名'],
            ['account', '支付宝帐号'],
            ['cash', '提现金额（元）', 'callback', function ($cash) {
                return $cash / 100;
            }],
            ['now_cash', '到账金额（元）', 'callback', function ($now_cash) {
                if ($now_cash == 0) {
                    return '';
                }
                return $now_cash / 100;
            }],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_withdrawal_status],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[8]);
            unset($search[9]);
            // 去掉显示列
            unset($items[0]);
        }
        //        if ($this->is_agent) {
        //            // 显示搜索项
        //            $search[] = ['text:3', 'merchant_id', '商户号'];
        //            // 显示列
        //            array_unshift($items, ['merchant_id', '商户', 'callback', function($value) {
        //                    return $value . '<br/>' . get_user_nickname($value);
        //                }, '', 'text-center']);
        //        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export_alipay', ['map' => urlencode(json_encode($map))]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $max_withdrawal_apply_count = pay_config('max_withdrawal_apply_count');

        $tips = "系统设置最多存在申请提现状态为｛{$max_withdrawal_apply_count}｝个！";

        $add_withdrawal_alipay = <<<EOF
<a title="申请支付宝提现" style="margin-bottom:6px;" class="btn btn-nm btn-primary" href="add_alipay" >
<i class="fa fa-plus-circle"></i>
申请支付宝提现
</a> 
EOF;

        if ($this->no_auth) {
            $info = MconfigModel::where(['id' => $this->merchant_id, 'status' => 1])->find();
            if (false === strpos($info['trade_type'], 'withdrawal')) {
                $add_withdrawal_alipay = '';
                $tips = '';
            }
        }

        // 是否开启手动提现
        if ($this->merchant_info['manual_withdrawal'] == 0) {
            $add_withdrawal_alipay = '';
            $tips = '';
        }

        // 是否开启支付宝提现
        if ($this->merchant_info['alipay_withdrawal'] == 0) {
            $add_withdrawal_alipay = '';
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('支付宝提现列表') // 设置页面标题
            ->setTableName('payment_withdrawal_alipay') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->setSearchArea($search) // 设置搜索参数
            ->setPageTips($tips)
            ->hideCheckbox()
            ->addColumns($items)
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮 
            ->setExtraHtml($add_withdrawal_alipay, 'toolbar_top')
            ->addRightButton('see_alipay', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see_alipay', ['id' => '__id__'])], true)
            ->addRightButton('edit_alipay', ['title' => '编辑', 'icon' => 'fa fa-pencil', 'href' => url('edit_alipay', ['id' => '__id__'])])
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->replaceRightButton(['status' => ['not in', '0,3,4']], '', 'edit_alipay') // 替换右侧按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = WithdrawalModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！');
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "提现订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'operation_id',
            'merchant_id',
            'bank_type',
            'bank_name',
            'name',
            'bank_card',
            'mobile',
            'id_card',
            'account_type',
            'account_opening_branch',
            'couplet_number',
            'province',
            'city',
            'cash',
            'now_cash',
            'status',
            'deduct_cash',
            'withdrawal_start_price',
            'withdrawal_rate',
            'order_id',
            'other_order_id',
            'create_time',
            'update_time',
        ];
        if ($this->no_auth) {
            unset($field[0]);
            unset($field[20]);
        }

        $cellName = [
            '操作号',
            '商户号',
            '银行卡类型',
            '收款银行名称',
            '收款人姓名',
            '收款银行卡',
            '收款人手机号',
            '收款人身份证',
            '账户类型',
            '开户支行',
            '联行号',
            '省份名称',
            '城市名称',
            '提现金额',
            '到账金额',
            '状态',
            '扣除金额',
            '每次提现开始价格',
            '提现费率',
            '本地订单号',
            '第三方订单号',
            '创建时间',
            '更新时间',
        ];
        if ($this->no_auth) {
            unset($cellName[0]);
            unset($cellName[20]);
        }
        $hide_info = 0;
        if ($this->no_auth) {
            $hide_info = 1;
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_withdrawal')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_withdrawal_status, $hide_info) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['now_cash'] /= 100;
                    $single['deduct_cash'] /= 100;
                    $single['withdrawal_start_price'] /= 100;
                    $single['status'] = $all_withdrawal_status[$single['status']];
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if ($hide_info) {
                        $single['bank_card'] = '****' . substr($single['bank_card'], 4);
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'deduct_cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 导出数据支付宝
     * @return mixed
     */
    public function export_alipay($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = WithdrawalAlipayModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！');
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "支付宝提现订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'operation_id',
            'merchant_id',
            'name',
            'account',
            'mobile',
            'cash',
            'now_cash',
            'status',
            'deduct_cash',
            'withdrawal_start_price',
            'withdrawal_rate',
            'order_id',
            'other_order_id',
            'create_time',
            'update_time',
        ];
        if ($this->no_auth) {
            unset($field[0]);
            unset($field[12]);
        }

        $cellName = [
            '操作号',
            '商户号',
            '收款人姓名',
            '支付宝帐号',
            '收款人手机号',
            '提现金额',
            '到账金额',
            '状态',
            '扣除金额',
            '每次提现开始价格',
            '提现费率',
            '本地订单号',
            '第三方订单号',
            '创建时间',
            '更新时间',
        ];
        if ($this->no_auth) {
            unset($cellName[0]);
            unset($cellName[12]);
        }
        $hide_info = 0;
        if ($this->no_auth) {
            $hide_info = 1;
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_withdrawal_alipay')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_withdrawal_status, $hide_info) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['now_cash'] /= 100;
                    $single['deduct_cash'] /= 100;
                    $single['withdrawal_start_price'] /= 100;
                    $single['status'] = $all_withdrawal_status[$single['status']];
                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if ($hide_info) {
                        $single['account'] = '****' . substr($single['account'], 4);
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'deduct_cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 是否开启手动提现
        if ($this->merchant_info['manual_withdrawal'] == 0) {
            $this->error("无提现权限！", url('index'));
        }

        $day_min_withdrawal = pay_config('day_min_withdrawal');
        $day_max_withdrawal = pay_config('day_max_withdrawal');
        $day_withdrawal_count = pay_config('day_withdrawal_count');
        $max_withdrawal_apply_count = pay_config('max_withdrawal_apply_count');
        $map = [];
        $cash = 0;
        if ($this->no_auth) {
            $map[] = ['merchant_id', '=', $this->merchant_id];
            $cash = WithdrawalModel::surplusCash($this->merchant_id);
        }
        $withdrawal_rate = MconfigModel::where(['id' => $this->merchant_id])->value('withdrawal_rate') ?: 0;
        $withdrawal_start_price = MconfigModel::where(['id' => $this->merchant_id])->value('withdrawal_start_price') ?: 0;

        $map[] = ['status', '=', 1];
        $bank_card = BankCardModel::where($map)->column('*', 'id');
        if ($bank_card) {
            foreach ($bank_card as $key => &$value) {
                $bank_card[$key] = '商户号：' . $value['merchant_id'] . '——收款银行名称：' . $value['bank_name'] . '——收款人姓名：' . $value['name'] . '——收款银行卡：' . $value['bank_card'] . '——开户支行：' . $value['account_opening_branch'];
            }
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }

            if ($data['manual'] == 'open') {
                // 验证
                $result = $this->validate($data, 'Withdrawal');
                // 验证失败 输出错误信息
                if (true !== $result) {
                    $this->error($result);
                }
                $withdrawals = $data;
            } else {
                // 验证
                $result = $this->validate($data, 'Withdrawal.close');
                // 验证失败 输出错误信息
                if (true !== $result) {
                    $this->error($result);
                }
                $bank_card_config = BankCardModel::where(['id' => $data['manual_select']])->find()->toArray();
                unset($bank_card_config['merchant_remark']);
                $withdrawals = array_merge($data, $bank_card_config);
            }

            $info = MconfigModel::where(['id' => $withdrawals['merchant_id'], 'status' => 1])->find();
            $withdrawals['withdrawal_rate'] = $info['withdrawal_rate'];
            $withdrawals['withdrawal_start_price'] = $info['withdrawal_start_price'] * 100;
            if (false === strpos($info['trade_type'], 'withdrawal')) {
                $this->error('商户没有开通提现功能！');
            }
            if ($withdrawals['cash'] < $day_min_withdrawal) {
                $this->error("系统设置商户每次最低提现{$day_min_withdrawal}元！");
            }
            if ($withdrawals['cash'] > $day_max_withdrawal) {
                $this->error("系统设置商户每次最多提现{$day_max_withdrawal}元！");
            }

            $withdrawals['cash'] *= 100;
            $withdrawals['deduct_cash'] = $withdrawals['cash'] + $withdrawals['cash'] * $withdrawals['withdrawal_rate'] + $withdrawals['withdrawal_start_price'];
            $cash = WithdrawalModel::surplusCash($withdrawals['merchant_id']);

            if ($withdrawals['deduct_cash'] > $cash) {
                $msg_deduct_cash = $withdrawals['deduct_cash'] / 100;
                $this->error("您的可提现余额不足，提现扣除金额为{$msg_deduct_cash}元！");
            }

            $merchant_surplus_cash = PaymentCash::where(['status' => 1, 'merchant_id' => $withdrawals['merchant_id']])->find();
            if (!$merchant_surplus_cash) {
                $this->error("商户钱包不存在或者被禁用！");
            }

            $now_day_withdrawal_count = WithdrawalModel::withdrawalCount($withdrawals['merchant_id'], 0);
            if ($now_day_withdrawal_count >= $max_withdrawal_apply_count) {
                $this->error("您有｛{$now_day_withdrawal_count}｝个在申请中，可以催客服快速处理！");
            }

            $now_day_withdrawal_count_ok = WithdrawalModel::withdrawalCount($withdrawals['merchant_id'], 1, date('Y-m-d'));
            if ($now_day_withdrawal_count_ok >= $day_withdrawal_count) {
                $this->error("今天商户已经提现{$now_day_withdrawal_count_ok}次了！");
            }

            $now_day_max_withdrawal = WithdrawalModel::withdrawalCash($withdrawals['merchant_id'], 1, date('Y-m-d'));
            if ($now_day_max_withdrawal >= $day_max_withdrawal * 100) {
                $this->error("系统设置商户每天最多提现{$day_max_withdrawal}元！");
            }

            $withdrawals['status'] = 0;                                         // 申请状态
            $withdrawals['order_id'] = date('ymdHis') . random(8);              // 平台订单号
            $withdrawals['create_time'] = time();                               // 创建时间
            $withdrawals['update_time'] = time();                               // 更新时间

            if ($temp = WithdrawalModel::create($withdrawals)) {

                try {
                    // 提现金额暂时冻结
                    PaymentCash::where(['merchant_id' => $withdrawals['merchant_id']])
                        ->inc('freeze_cash', $withdrawals['deduct_cash'])
                        ->dec('cash', $withdrawals['deduct_cash'])
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    payment_error_log(850000, $withdrawals, $e->getMessage());
                    $this->error("单次提现更新金额有误，请联系程序员处理！");
                }

                // 记录行为
                action_log('payment_withdrawal_add', 'withdrawal', $temp['order_id'], UID, json_encode($temp));
                $this->success('新增成功！', url('index'));
            } else {
                $this->error('新增失败！');
            }
        }

        $items = [
            ['radio', 'manual', '手动填写', '<code>点击开启手动填写参数</code>', ['close' => '关闭', 'open' => '开启'], 'close'],
            ['select', 'manual_select', '选择已经设置过的银行卡', '', $bank_card],
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['select', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['text', 'bank_name', '收款银行名称', '必填：比如:<code>中国工商银行</code>'],
            ['text', 'name', '收款人姓名', '必填：比如:<code>我是谁</code>'],
            ['text', 'bank_card', '收款银行卡', '必填：比如:<code>6217002870051515818</code>'],
            ['text', 'mobile', '收款人手机号', '可填：比如:<code>13888888888</code>说明：如果填写，提现成功可能会给此手机号发送短信。'],
            ['text', 'id_card', '收款人身份证', '必填：不清楚填0<code>身份证号码</code>'],
            ['text', 'account_opening_branch', '开户支行', '必填：比如:<code>工商银行广州高新支行</code>'],
            ['radio', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['text', 'couplet_number', '联行号', '<code>公户</code>账户必须填写：比如:<code>103521003839</code>：<a target="_blank" href="https://www.hebbank.com/corporbank/otherBankQueryWeb.do">查看地址</a>'],
            ['text', 'province', '省份名称', '必填：比如:<code>广东省</code>'],
            ['text', 'city', '城市名称', '必填：比如:<code>广州市</code>'],
            ['text', 'cash', '提现金额', '必填（整数）：比如:<code>10000</code>', intval($cash / 100)],
            ['textarea', 'merchant_remark', '商户备注'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->no_auth) {
            unset($items[2]);
        }
        $open = 'merchant_id,bank_type,bank_name,name,id_card,mobile,bank_card,account_type,account_opening_branch,couplet_number,province,city';

        $tips = "请勿填错！系统设置商户每天最多提现{$day_withdrawal_count}次，每次最低提现{$day_min_withdrawal}元，每天最多提现{$day_max_withdrawal}元，单笔提现最好不要大于50000元！"
            . "<br/>提现状态分：'申请提现'、'提现成功'、'驳回'、 '待确认'、'客服处理中'！"
            . "<br/>流程一般是：<font color='#295995'>当您申请提现后，通知客服（财务）</font>，客服第一时间会把状态改成（客服处理中），当客服把钱转账到您（银行卡）那边的时候，客服会再把状态改成（待确认），您那边确认收到钱后，通知客服，然后客服再把状态改成（提现成功）！";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('申请提现') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->setTrigger('manual', 'open,close', 'cash,merchant_remark')
            ->setTrigger('manual', 'open', $open)
            ->setTrigger('manual', 'close', 'manual_select')
            ->fetch();
    }

    /**
     * 新增支付宝
     * @return mixed
     */
    public function add_alipay()
    {
        // 是否开启手动提现
        if ($this->merchant_info['manual_withdrawal'] == 0 || $this->merchant_info['alipay_withdrawal'] == 0) {
            $this->error("无支付宝提现权限！", url('index_alipay'));
        }

        $day_min_withdrawal = pay_config('day_min_withdrawal');
        $day_max_withdrawal = pay_config('day_max_withdrawal');
        $day_withdrawal_count = pay_config('day_withdrawal_count');
        $max_withdrawal_apply_count = pay_config('max_withdrawal_apply_count');
        $map = [];
        $cash = 0;
        if ($this->no_auth) {
            $map[] = ['merchant_id', '=', $this->merchant_id];
            $cash = WithdrawalAlipayModel::surplusCash($this->merchant_id);
        }
        $withdrawal_rate = MconfigModel::where(['id' => $this->merchant_id])->value('withdrawal_rate') ?: 0;
        $withdrawal_start_price = MconfigModel::where(['id' => $this->merchant_id])->value('withdrawal_start_price') ?: 0;

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }
            // 验证
            $result = $this->validate($data, 'WithdrawalAlipay');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }
            $withdrawals = $data;

            $info = MconfigModel::where(['id' => $withdrawals['merchant_id'], 'status' => 1])->find();
            $withdrawals['withdrawal_rate'] = $info['withdrawal_rate'];
            $withdrawals['withdrawal_start_price'] = $info['withdrawal_start_price'] * 100;
            if (false === strpos($info['trade_type'], 'withdrawal')) {
                $this->error('商户没有开通提现功能！');
            }
            if ($withdrawals['cash'] < $day_min_withdrawal) {
                $this->error("系统设置商户每次最低提现{$day_min_withdrawal}元！");
            }
            if ($withdrawals['cash'] > $day_max_withdrawal) {
                $this->error("系统设置商户每次最多提现{$day_max_withdrawal}元！");
            }

            $withdrawals['cash'] *= 100;
            $withdrawals['deduct_cash'] = $withdrawals['cash'] + $withdrawals['cash'] * $withdrawals['withdrawal_rate'] + $withdrawals['withdrawal_start_price'];
            $cash = WithdrawalAlipayModel::surplusCash($withdrawals['merchant_id']);

            if ($withdrawals['deduct_cash'] > $cash) {
                $msg_deduct_cash = $withdrawals['deduct_cash'] / 100;
                $this->error("您的可提现余额不足，提现扣除金额为{$msg_deduct_cash}元！");
            }

            $merchant_surplus_cash = PaymentCash::where(['status' => 1, 'merchant_id' => $withdrawals['merchant_id']])->find();
            if (!$merchant_surplus_cash) {
                $this->error("商户钱包不存在或者被禁用！");
            }

            $now_day_withdrawal_count = WithdrawalAlipayModel::withdrawalCount($withdrawals['merchant_id'], 0);
            if ($now_day_withdrawal_count >= $max_withdrawal_apply_count) {
                $this->error("您有｛{$now_day_withdrawal_count}｝个在申请中，可以催客服快速处理！");
            }

            $now_day_withdrawal_count_ok = WithdrawalAlipayModel::withdrawalCount($withdrawals['merchant_id'], 1, date('Y-m-d'));
            if ($now_day_withdrawal_count_ok >= $day_withdrawal_count) {
                $this->error("今天商户已经提现{$now_day_withdrawal_count_ok}次了！");
            }

            $now_day_max_withdrawal = WithdrawalAlipayModel::withdrawalCash($withdrawals['merchant_id'], 1, date('Y-m-d'));
            if ($now_day_max_withdrawal >= $day_max_withdrawal * 100) {
                $this->error("系统设置商户每天最多提现{$day_max_withdrawal}元！");
            }

            $withdrawals['status'] = 0;                                         // 申请状态
            $withdrawals['order_id'] = date('ymdHis') . random(8);              // 平台订单号
            $withdrawals['create_time'] = time();                               // 创建时间
            $withdrawals['update_time'] = time();                               // 更新时间

            if ($temp = WithdrawalAlipayModel::create($withdrawals)) {

                try {
                    // 提现金额暂时冻结
                    PaymentCash::where(['merchant_id' => $withdrawals['merchant_id']])
                        ->inc('freeze_cash', $withdrawals['deduct_cash'])
                        ->dec('cash', $withdrawals['deduct_cash'])
                        ->update(['update_time' => time()]);
                } catch (\Exception $e) {
                    payment_error_log(850001, $withdrawals, $e->getMessage());
                    $this->error("支付宝提现：单次提现更新金额有误，请联系程序员处理！");
                }

                // 记录行为
                action_log('payment_withdrawal_alipay_add', 'withdrawal_alipay', $temp['order_id'], UID, json_encode($temp));
                $this->success('新增成功！', url('index_alipay'));
            } else {
                $this->error('新增失败！');
            }
        }

        $items = [
            ['select', 'merchant_id', '商户号', '', all_merchant()],
            ['text', 'name', '收款人姓名', '必填：比如:<code>我是谁</code>'],
            ['text', 'account', '支付宝帐号', '必填：比如:<code>邮箱或手机号</code>'],
            ['text', 'mobile', '收款人手机号', '可填：比如:<code>13888888888</code>说明：如果填写，提现成功可能会给此手机号发送短信。'],
            ['text', 'cash', '提现金额', '必填（整数）：比如:<code>10000</code>', intval($cash / 100)],
            ['textarea', 'merchant_remark', '商户备注'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        if ($this->no_auth) {
            unset($items[0]);
        }
        $tips = "请勿填错！系统设置商户每天最多提现{$day_withdrawal_count}次，每次最低提现{$day_min_withdrawal}元，每天最多提现{$day_max_withdrawal}元，单笔提现最好不要大于50000元！"
            . "<br/>提现状态分：'申请提现'、'提现成功'、'驳回'、 '待确认'、'客服处理中'！"
            . "<br/>流程一般是：<font color='#295995'>当您申请提现后，通知客服（财务）</font>，客服第一时间会把状态改成（客服处理中），当客服把钱转账到您（支付宝）那边的时候，客服会再把状态改成（待确认），您那边确认收到钱后，通知客服，然后客服再把状态改成（提现成功）！";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('申请支付宝提现') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 上传
     * @return mixed
     */
    public function up()
    {
        // 是否开启手动提现
        if ($this->merchant_info['manual_withdrawal'] == 0) {
            $this->error("无提现权限！", url('index'));
        }

        $merchant_id = $this->merchant_id;

        $withdrawal_status = PaymentCash::where(['merchant_id' => $merchant_id])->value('status') ?: 0;

        $day_min_withdrawal = pay_config('day_min_withdrawal');
        $day_max_withdrawal = pay_config('day_max_withdrawal');
        $day_upload_withdrawal_count = pay_config('day_upload_withdrawal_count');
        $max_withdrawal_apply_count = pay_config('max_withdrawal_apply_count');
        $withdrawal_rate = MconfigModel::where(['id' => $merchant_id])->value('withdrawal_rate') ?: 0;
        $withdrawal_start_price = MconfigModel::where(['id' => $merchant_id])->value('withdrawal_start_price') ?: 0;
        $withdrawal_start_price = $withdrawal_start_price * 100;

        $cash = WithdrawalModel::surplusCash($merchant_id);
        $cash = $cash / 100;

        $day_count = Attachment::where(['uid' => $this->uid, 'module' => 'payment', 'ext' => 'xls'])->whereTime('create_time', 'today')->count();
        if ($day_count > $day_upload_withdrawal_count) {
            $this->error("您今天上传提现文件已经｛{$day_upload_withdrawal_count}｝次了！");
        }

        // 前端控制上传次数
        $js = <<<EOF
            <script type="text/javascript">
                var temp=1;
            var dp_file_upload_success = function () {
                
                html_temp = document.getElementById('html_temp').innerHTML;       
                static_count= Number(html_temp)+Number(temp);   
                document.getElementById('html_temp').innerHTML=static_count;
                if(static_count>$day_upload_withdrawal_count){
                    window.location.href='index';  
                }
                
              };
            </script>
EOF;
        $html = "<div id='html_temp' style='display:none'>{$day_count}</div>";

        $mconfig = MconfigModel::where(['id' => $this->merchant_id, 'status' => 1])->find();
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (!$withdrawal_status) {
                $this->error('商户已经被禁止提现！');
            }

            $file = input('file');
            $up_file = Attachment::where(['id' => $file])->find();
            if (!$file || !$up_file) {
                $this->error('没有上传提现文件！');
            }

            // 记录行为
            action_log('payment_withdrawal_up', 'withdrawal', $merchant_id, UID);

            //$up_file_dir = str_replace("/", DS, $up_file['path']);
            //$full_path = ROOT_PATH . 'public' . "\\" . $up_file_dir;

            $full_path = getcwd() . get_file_path($file);

            $import = plugin_action('Excel/Excel/import', [$full_path]);

            if ($import['error'] != 0) {
                $this->error($import['message']);
            }
            $all_data = $import['data'][0]['Content'];

            array_shift($all_data);    // 将数组开头的单元移出数组
            if (empty($all_data)) {
                $this->error('提现数据为空！');
            }

            $now_withdrawal_count = WithdrawalModel::withdrawalCount($merchant_id, 0, date('Y-m-d'));
            if (count($all_data) + $now_withdrawal_count > $max_withdrawal_apply_count) {
                $this->error("申请提现次数已经大于系统设置｛{$max_withdrawal_apply_count}｝次！");
            }

            $withdrawal_cash_sum = 0;

            foreach ($all_data as $key => $value) {
                $row = $key + 1;
                $title = "第{$row}行数据错误，错误说明";

                if (!in_array($value[0], ['借记卡', '信用卡', '贷记卡'])) {
                    $this->error("{$title}：银行卡类型(借记卡、信用卡、贷记卡)！");
                }
                if (empty($value[1])) {
                    $this->error("{$title}：银行名称（必填，根据模板填写银行名称，否则，可能会失败）！");
                }
                if (empty($value[2])) {
                    $this->error("{$title}：收款人姓名（不能有误）！");
                }
                if (empty($value[3])) {
                    $this->error("{$title}：收款人身份证（不能有误）！");
                }
                if (empty($value[5])) {
                    $this->error("{$title}：收款方银行账号（推荐19位）！");
                }
                if (!in_array($value[6], ['私户', '公户'])) {
                    $this->error("{$title}：账户类型(私户、公户)！");
                }
                if (empty($value[7])) {
                    $this->error("{$title}：开户支行！");
                }
                if (empty($value[9])) {
                    $this->error("{$title}：省份名称！");
                }
                if (empty($value[10])) {
                    $this->error("{$title}：城市名称！");
                }
                if (!is_numeric($value[12]) || $value[12] < $day_min_withdrawal || $value[12] > $day_max_withdrawal) {
                    $this->error("{$title}：提现金额（元）,必须是数字和大于等于{$day_min_withdrawal}且小于等于{$day_max_withdrawal}！");
                }
                $withdrawal_cash_sum = $withdrawal_cash_sum + $value[12];
            }

            $withdrawal_cash_sums = $withdrawal_cash_sum + count($all_data) * $withdrawal_start_price + floor($withdrawal_cash_sum * $withdrawal_rate);

            if ($cash < $withdrawal_cash_sums) {
                $this->error("上传文件的提现总金额，大于现在的可结算金额｛{$cash}｝元！");
            }
            // 插入提现表
            foreach ($all_data as $key => $value) {
                $arr['operation_id'] = 0;
                $arr['merchant_id'] = $merchant_id;
                $arr['bank_type'] = $value[0];
                $arr['bank_name'] = $value[1];
                $arr['name'] = $value[2];
                $arr['id_card'] = $value[3];
                $arr['mobile'] = $value[4];
                $arr['bank_card'] = $value[5];
                $arr['account_type'] = $value[6];
                $arr['account_opening_branch'] = $value[7];
                $arr['couplet_number'] = $value[8];
                $arr['province'] = $value[9];
                $arr['city'] = $value[10];
                $arr['merchant_remark'] = $value[11];
                $arr['cash'] = intval(strval($value[12] * 100));
                $arr['deduct_cash'] = $arr['cash'] + $withdrawal_start_price + floor($arr['cash'] * $withdrawal_rate);
                $arr['withdrawal_start_price'] = $withdrawal_start_price;
                $arr['withdrawal_rate'] = $withdrawal_rate;
                $arr['order_id'] = date('ymdHis') . random(8);
                $arr['other_order_id'] = '';
                $arr['remark'] = '';
                $arr['programmer_remark'] = '';
                $arr['create_time'] = time();
                $arr['update_time'] = 0;
                $arr['status'] = 0;
                // 捕获异常,可能表数据写入失败

                $now_merchant_cash = WithdrawalModel::surplusCash($merchant_id);
                if ($now_merchant_cash < $arr['deduct_cash']) {
                    $this->error("可提现金额不足！");
                }

                try {
                    // 插入提现表
                    WithdrawalModel::create($arr);
                    try {
                        // 提现金额暂时冻结
                        PaymentCash::where(['merchant_id' => $merchant_id])
                            ->inc('freeze_cash', $arr['deduct_cash'])
                            ->dec('cash', $arr['deduct_cash'])
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        payment_error_log(850003, $arr, $e->getMessage());
                        $this->error("更新提现金额有误，请联系程序员处理！");
                    }
                } catch (\Exception $e) {
                    payment_error_log(850002, $arr, $e->getMessage());
                    $this->error("导入出错了，请联系程序员处理！");
                }
            }

            $this->success('操作成功', url('index'));
        }
        $items = [
            ['file', 'file', '文件', '上传提现文件.xls', '', '1024', 'xls'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $submit = ['submit' => '导入提现'];
        $btn = ['back'];
        if ($day_min_withdrawal > $cash || !$withdrawal_status || false === strpos($mconfig['trade_type'], 'withdrawal')) {
            $items = [];
            $submit = [];
            $btn = ['back', 'submit'];
        }
        return ZBuilder::make('form')
            ->setPageTitle('导入提现') // 设置页面标题
            ->setPageTips("系统设置每天最多上传提现文件次数为{$day_upload_withdrawal_count}次！<br/><br/>每次最低提现金额为｛{$day_min_withdrawal}｝元，每天最多提现金额为｛{$day_max_withdrawal}｝元。<br/><br/>您当前可提现金额为｛{$cash}｝元，请合理安排提现金额。")
            ->addFormItems($items)
            ->hideBtn($btn)
            ->setBtnTitle($submit)
            ->setExtraJs($js) // 引入自定义的外部js文件
            ->setExtraHtml($html)
            ->assign('empty_tips', '暂时不满足提现条件')
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数');
        }
        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];
        // 获取数据
        $info = WithdrawalModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('权限不足！');
            }
            unset($all_withdrawal_status[8]);
        }

        $info['cash'] /= 100;
        $info['now_cash'] /= 100;
        $info['deduct_cash'] /= 100;
        $info['withdrawal_start_price'] /= 100;

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['static', 'bank_name', '收款银行名称'],
            ['static', 'name', '收款人姓名'],
            ['static', 'bank_card', '收款银行卡'],
            ['static', 'mobile', '收款人手机号'],
            ['static', 'id_card', '收款人身份证'],
            ['static', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['static', 'account_opening_branch', '开户支行'],
            ['static', 'couplet_number', '联行号'],
            ['static', 'province', '省份名称'],
            ['static', 'city', '城市名称'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '状态', '', $all_withdrawal_status, '', '', 'disabled'],
            ['static', 'cash', '提现金额（元）'],
            ['static', 'now_cash', '到账金额（元）'],
            ['static', 'deduct_cash', '扣除金额（元）'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'withdrawal_start_price', '每次提现开始手续费'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'order_id', '平台订单号'],
            ['textarea', 'remark', '本地备注[:无]', '', '', 'disabled', ''],
            ['static', 'other_order_id', '第三方订单号'],
            ['textarea', 'programmer_remark', '程序员备注[:无]', '', '', 'disabled', ''],
            ['static', 'operation_id', '操作号', '商户名称：' . get_user_nickname($info['operation_id'])],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];
        if ($this->no_auth) {
            unset($items[22]);
            unset($items[23]);
            unset($items[24]);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 查看支付宝
     * @param null $id 
     * @return mixed
     */
    public function see_alipay($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数');
        }
        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中', 8 => '程序员查看'];
        // 获取数据
        $info = WithdrawalAlipayModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('权限不足！');
            }
            unset($all_withdrawal_status[8]);
        }

        $info['cash'] /= 100;
        $info['now_cash'] /= 100;
        $info['deduct_cash'] /= 100;
        $info['withdrawal_start_price'] /= 100;

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'name', '收款人姓名'],
            ['static', 'account', '支付宝帐号'],
            ['static', 'mobile', '收款人手机号'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '状态', '', $all_withdrawal_status, '', '', 'disabled'],
            ['static', 'cash', '提现金额（元）'],
            ['static', 'now_cash', '到账金额（元）'],
            ['static', 'deduct_cash', '扣除金额（元）'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'withdrawal_start_price', '每次提现开始手续费'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'order_id', '平台订单号'],
            ['textarea', 'remark', '本地备注[:无]', '', '', 'disabled', ''],
            ['static', 'other_order_id', '第三方订单号'],
            ['textarea', 'programmer_remark', '程序员备注[:无]', '', '', 'disabled', ''],
            ['static', 'operation_id', '操作号', '商户名称：' . get_user_nickname($info['operation_id'])],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];
        if ($this->no_auth) {
            unset($items[14]);
            unset($items[15]);
            unset($items[16]);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id  id
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = WithdrawalModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }
        if (!in_array($info['status'], [0, 3, 4])) {
            $this->error('提现状态不是（申请提现和待确认和客服处理中）状态！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'Withdrawal.edit');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }
            if ($data['status'] == 0) {
                $this->error('提现状态，请选择提现成功、驳回、待确认、客服处理中！');
            }
            if ($data['status'] == $info['status']) {
                $this->error('提现状态，请选择其它提现状态！');
            }
            if (in_array($data['status'], [1, 2])) {
                if (!$data['remark']) {
                    $this->error('请输入本地备注！');
                }
            }

            $data['operation_id'] = $this->merchant_id;
            if ($data['status'] == 1) {
                if ($data['now_cash'] < 1) {
                    $this->error('请输入（合理）到账金额！');
                }
                $data['now_cash'] = $data['now_cash'] * 100;
            }

            if (WithdrawalModel::update($data)) {

                $withdrawal = WithdrawalModel::where('order_id', $data['order_id'])->find();
                $withdrawal_deduct_cash = $withdrawal['deduct_cash'];

                // 记录行为
                action_log('payment_withdrawal_edit', 'withdrawal', $withdrawal['order_id'], UID, json_encode($withdrawal));

                // 商户号冻结金额
                $merchant_freeze_cash = PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                    ->value('freeze_cash');

                // 提现成功
                if ($data['status'] == 1) {

                    if ($withdrawal_deduct_cash > $merchant_freeze_cash) {
                        $programmer_remark = '状态已经修改,但是商户冻结金额不足,请联系程序员处理：代号100';
                        WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850004, $withdrawal, $programmer_remark);
                        $this->error("操作失败，{$programmer_remark}", url('index'));
                    }

                    try {
                        PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                            ->inc('withdrawal_count')
                            ->inc('withdrawal_sum_cash', $withdrawal_deduct_cash)
                            ->dec('freeze_cash', $withdrawal_deduct_cash)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {

                        $programmer_remark = '状态已经修改,但是商户冻结金额扣除失败,请联系程序员处理：代号200';
                        WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850005, $withdrawal, $e->getMessage());
                        $this->error("操作失败，{$programmer_remark}", url('index'));
                    }
                }

                // 驳回
                if ($data['status'] == 2) {

                    if ($withdrawal_deduct_cash > $merchant_freeze_cash) {
                        $programmer_remark = '状态已经修改,但是商户冻结金额不足,请联系程序员处理：代号300';
                        WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850006, $withdrawal, $programmer_remark);
                        $this->error("操作失败，{$programmer_remark}", url('index'));
                    }

                    try {
                        // 提现冻结金额恢复
                        PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                            ->dec('freeze_cash', $withdrawal_deduct_cash)
                            ->inc('cash', $withdrawal_deduct_cash)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {

                        $programmer_remark = '状态已经修改,但是提现冻结金额恢复有误,请联系程序员处理：代号400';
                        WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);

                        payment_error_log(850007, $withdrawal, $e->getMessage());
                        $this->error("操作失败，{$programmer_remark}", url('index'));
                    }
                }

                // 待确认
                if ($data['status'] == 3) {

                    WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                        ->update([
                            'status' => 3,
                            'update_time' => time(),
                        ]);
                }

                // 客服处理中
                if ($data['status'] == 4) {

                    WithdrawalModel::where(['order_id' => $withdrawal['order_id']])
                        ->update([
                            'status' => 4,
                            'update_time' => time(),
                        ]);
                }

                $this->success('操作成功', url('index'));
            } else {
                payment_error_log(850008, $data);
                $this->error('操作失败，更新提现状态失败！', url('index'));
            }
        }

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中'];
        if ($info['status'] == 3) {
            unset($all_withdrawal_status[0]);
            unset($all_withdrawal_status[4]);
        }

        $items = [
            ['hidden', 'order_id', $id],
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'bank_type', '银行卡类型', '', ['借记卡' => '借记卡', '信用卡' => '信用卡', '贷记卡' => '贷记卡']],
            ['static', 'bank_name', '收款银行名称'],
            ['static', 'name', '收款人姓名'],
            ['static', 'bank_card', '收款银行卡'],
            ['static', 'mobile', '收款人手机号'],
            ['static', 'id_card', '收款人身份证'],
            ['static', 'account_type', '账户类型', '', ['私户' => '私户', '公户' => '公户'], '私户'],
            ['static', 'account_opening_branch', '开户支行'],
            ['static', 'couplet_number', '联行号'],
            ['static', 'province', '省份名称'],
            ['static', 'city', '城市名称'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '提现状态', '', $all_withdrawal_status, '', '', ''],
            ['static', 'cashs', '提现金额（元）', '', $info['cash'] / 100],
            ['static', 'deduct_cashs', '扣除金额（元）', '', $info['deduct_cash'] / 100],
            ['static', 'withdrawal_start_price', '每次提现开始手续费'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'order_id', '本地提现订单号'],
            ['text', 'now_cash', '到账金额', '实际上银行卡到账金额（请勿填错）'],
            ['text', 'other_order_id', '第三方订单号', '类似银行交易号，做凭证'],
            ['textarea', 'remark', '本地备注', '', '', '', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $tips = "请勿填错！<br/>当商户申请提现后，您选择操作提现状态时，只能选择提现成功、驳回、待确认。<br/>"
            . "当您选择（驳回）的时候，只需输入备注信息即可。<br/>"
            . "当您选择（待确认）的时候，联系商户确认是否到账。<br/>"
            . "当您选择（提现成功）的时候，输入第三方订单号（类似银行交易号），和备注信息即可。<br/>"
            . "当您选择（提现成功）的时候，系统将自动扣除商户相对应的钱包余额。<br/>";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->setFormData($info) // 设置表单数据
            ->setTrigger('status', '1', 'now_cash,other_order_id')
            ->fetch();
    }

    /**
     * 编辑支付宝
     * @param null $id  id
     * @return mixed
     */
    public function edit_alipay($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = WithdrawalAlipayModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }
        if (!in_array($info['status'], [0, 3, 4])) {
            $this->error('提现状态不是（申请提现和待确认和客服处理中）状态！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'WithdrawalAlipay.edit');
            // 验证失败 输出错误信息
            if (true !== $result) {
                $this->error($result);
            }
            if ($data['status'] == 0) {
                $this->error('提现状态，请选择提现成功、驳回、待确认、客服处理中！');
            }
            if ($data['status'] == $info['status']) {
                $this->error('提现状态，请选择其它提现状态！');
            }
            if (in_array($data['status'], [1, 2])) {
                if (!$data['remark']) {
                    $this->error('请输入本地备注！');
                }
            }

            $data['operation_id'] = $this->merchant_id;
            if ($data['status'] == 1) {
                if ($data['now_cash'] < 1) {
                    $this->error('请输入（合理）到账金额！');
                }
                $data['now_cash'] = $data['now_cash'] * 100;
            }

            if (WithdrawalAlipayModel::update($data)) {

                $withdrawal = WithdrawalAlipayModel::where('order_id', $data['order_id'])->find();
                $withdrawal_deduct_cash = $withdrawal['deduct_cash'];

                // 记录行为
                action_log('payment_withdrawal_alipay_edit', 'withdrawal_alipay', $withdrawal['order_id'], UID, json_encode($withdrawal));

                // 商户号冻结金额
                $merchant_freeze_cash = PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                    ->value('freeze_cash');

                // 提现成功
                if ($data['status'] == 1) {

                    if ($withdrawal_deduct_cash > $merchant_freeze_cash) {
                        $programmer_remark = '支付宝提现：状态已经修改,但是商户冻结金额不足,请联系程序员处理：代号100';
                        WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850009, $withdrawal, $programmer_remark);
                        $this->error("操作失败，{$programmer_remark}", url('index_alipay'));
                    }

                    try {
                        PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                            ->inc('withdrawal_count')
                            ->inc('withdrawal_sum_cash', $withdrawal_deduct_cash)
                            ->dec('freeze_cash', $withdrawal_deduct_cash)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {

                        $programmer_remark = '支付宝提现：状态已经修改,但是商户冻结金额扣除失败,请联系程序员处理：代号200';
                        WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850010, $withdrawal, $e->getMessage());
                        $this->error("操作失败，{$programmer_remark}", url('index_alipay'));
                    }
                }

                // 驳回
                if ($data['status'] == 2) {

                    if ($withdrawal_deduct_cash > $merchant_freeze_cash) {
                        $programmer_remark = '支付宝提现：状态已经修改,但是商户冻结金额不足,请联系程序员处理：代号300';
                        WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);
                        payment_error_log(850011, $withdrawal, $programmer_remark);
                        $this->error("操作失败，{$programmer_remark}", url('index_alipay'));
                    }

                    try {
                        // 提现冻结金额恢复
                        PaymentCash::where(['merchant_id' => $withdrawal['merchant_id']])
                            ->dec('freeze_cash', $withdrawal_deduct_cash)
                            ->inc('cash', $withdrawal_deduct_cash)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {

                        $programmer_remark = '支付宝提现：状态已经修改,但是提现冻结金额恢复有误,请联系程序员处理：代号400';
                        WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                            ->update([
                                'programmer_remark' => $programmer_remark,
                                'status' => 8,
                                'update_time' => time(),
                            ]);

                        payment_error_log(850012, $withdrawal, $e->getMessage());
                        $this->error("操作失败，{$programmer_remark}", url('index_alipay'));
                    }
                }

                // 待确认
                if ($data['status'] == 3) {

                    WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                        ->update([
                            'status' => 3,
                            'update_time' => time(),
                        ]);
                }

                // 客服处理中
                if ($data['status'] == 4) {

                    WithdrawalAlipayModel::where(['order_id' => $withdrawal['order_id']])
                        ->update([
                            'status' => 4,
                            'update_time' => time(),
                        ]);
                }

                $this->success('操作成功', url('index_alipay'));
            } else {
                payment_error_log(850013, $data);
                $this->error('支付宝提现：操作失败，更新提现状态失败！', url('index_alipay'));
            }
        }

        $all_withdrawal_status = [0 => '申请提现', 1 => '提现成功', 2 => '驳回', 3 => '待确认', 4 => '客服处理中'];
        if ($info['status'] == 3) {
            unset($all_withdrawal_status[0]);
            unset($all_withdrawal_status[4]);
        }

        $items = [
            ['hidden', 'order_id', $id],
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'name', '收款人姓名'],
            ['static', 'account', '支付宝帐号'],
            ['static', 'mobile', '收款人手机号'],
            ['textarea', 'merchant_remark', '商户备注[:无]', '', '', 'disabled', ''],
            ['radio', 'status', '提现状态', '', $all_withdrawal_status, '', '', ''],
            ['static', 'cashs', '提现金额（元）', '', $info['cash'] / 100],
            ['static', 'deduct_cashs', '扣除金额（元）', '', $info['deduct_cash'] / 100],
            ['static', 'withdrawal_start_price', '每次提现开始手续费'],
            ['static', 'withdrawal_rate', '提现费率'],
            ['static', 'order_id', '本地提现订单号'],
            ['text', 'now_cash', '到账金额', '实际上银行卡到账金额（请勿填错）'],
            ['text', 'other_order_id', '第三方订单号', '类似银行交易号，做凭证'],
            ['textarea', 'remark', '本地备注', '', '', '', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $tips = "请勿填错！<br/>当商户申请提现后，您选择操作提现状态时，只能选择提现成功、驳回、待确认。<br/>"
            . "当您选择（驳回）的时候，只需输入备注信息即可。<br/>"
            . "当您选择（待确认）的时候，联系商户确认是否到账。<br/>"
            . "当您选择（提现成功）的时候，输入第三方订单号（类似银行交易号），和备注信息即可。<br/>"
            . "当您选择（提现成功）的时候，系统将自动扣除商户相对应的钱包余额。<br/>";

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->setFormData($info) // 设置表单数据
            ->setTrigger('status', '1', 'now_cash,other_order_id')
            ->fetch();
    }
}
